<template>
  <div>
    <el-empty v-if="!buildingList.length" />
    <div class="building-list" v-else>
      <div v-for="(item1, idx1) in buildingList" :key="idx1">
        <div class="title" v-if="!isFirezone">{{ item1.name }}</div>
        <div class="list">
          <div class="item" v-for="(item2, idx2) in item1.list" :key="idx1 + '_' + idx2" :title="item2.fnameL2" :class="{ active: item2.fid === building.fid }" @click="onSelectBuilding(item2)">
            <svg-icon class="icon" :icon-class="item1.icon" color="#74a8f8" />
            <div class="ellipsis2">{{ item2.fnameL2 }}</div>
          </div>
        </div>
      </div>
    </div>

    <LineDrawPlane :title="lineDraw.title" :show.sync="lineDraw.show" :draw-areas.sync="lineDraw.drawAreas" :background-images="lineDraw.images" :current-image.sync="lineDraw.drawFileId" @cancel="onDrawCancel" @confirm="onDrawConfirm" />
  </div>
</template>
<script>
// 选择公区
import { listFile } from '@/api/baseManage/buildingManage'
import LineDrawPlane from '@/components/LineDrawPlane/LineDrawPlane'
export default {
  name: 'PublicArea',
  components: { LineDrawPlane },
  props: {
    buildings: { type: Array, default: () => [] },
    isFirezone: { type: Boolean, default: false },
    currArea: { type: Object, default: () => ({ fileId: '' }) }
  },
  data() {
    return {
      buildingList: [],
      building: {},
      lineDraw: {
        title: '',
        show: false,
        images: [],
        drawFileId: 0, // 当前图片ID
        drawAreas: [] // 当前绘线数据
      }
    }
  },
  watch: {
    buildings: {
      deep: true,
      immediate: true,
      handler(val) {
        this.building = {}
        const data = val || []

        // 分组展示
        const obj = {
          1: { buildType: 1, name: '景观', list: [], icon: 'scenery' },
          2: { buildType: 2, name: '停车场', list: [], icon: 'park' },
          3: { buildType: 3, name: '地下室', list: [], icon: 'under' },
          // 4: { buildType: 4, name: '桩基', list: [], icon: 'pile' }
          5: { buildType: 5, name: '防火分区', list: [], icon: 'firezone' }
        }
        const list = this.isFirezone ? data.filter(i => i.publicareatype === 5) : data.filter(i => [1, 2, 3].includes(i.publicareatype))
        list.map(i => obj[i.publicareatype] && obj[i.publicareatype].list.push(i))
        this.buildingList = Object.values(obj).filter(i => i.list.length)
      }
    }
  },
  methods: {
    async onSelectBuilding(building) {
      const currArea = this.currArea || {}
      this.building = {}
      // 取消上次已选
      this.$emit('cancel')

      // 防火分区不画图
      if (this.isFirezone) {
        this.building = building
        const position = { buildingId: building.fid, shortName: building.fnameL2 }
        this.$emit('ok', { building, position })
        return
      }

      const loading = this.$loading({ lock: true, text: '获取位置图片', spinner: 'el-icon-loading', background: 'rgba(255, 255, 255, 0.2)' })
      const res = await listFile(building.fid).catch(() => false)
      loading.close()
      if (res === false) return this.$message.error('获取位置图片失败')

      const files = res.data || []
      if (!files.length) return this.$alert('暂无位置图片，不能选择该位置。请先前往 “基础管控 → 基础工程管理” 添加位置图片。', '提示').catch(() => false)

      const drawArea = currArea.drawArea
      let drawData = []

      // 判断是之前涂抹时选的位置，且是涂抹的图片，才显示涂抹记录
      // const isDrewBuilding = currArea.buildingId === building.fid
      const isDrewFileId = currArea.publlicFileId && files.map(i => i + '').includes(currArea.publlicFileId)
      // if (drawArea && isDrewBuilding && isDrewFileId) {
      if (drawArea && isDrewFileId) {
        if (typeof drawArea === 'object') drawData = drawArea
        else if (typeof drawArea === 'string') {
          try {
            drawData = JSON.parse(drawArea)
          } catch (err) {
            console.error('parse drawArea error', err)
          }
        }
      }

      this.building = building

      this.lineDraw = {
        title: building.fnameL2,
        show: false,
        images: files,
        drawFileId: currArea.publlicFileId || 0,
        drawAreas: drawData
      }
      this.$nextTick(() => (this.lineDraw.show = true))
    },
    onDrawCancel() {
      this.building = {}
      // this.lineDraw.show = false
    },
    onDrawConfirm(data) {
      if (!data.length) return this.$message.info('请绘制区域')

      const { currArea, building } = this
      const { drawFileId } = this.lineDraw
      const position = {
        buildingId: building.fid,
        taskFileId: currArea.taskFileId,
        fileId: currArea.fileId,
        shortName: building.fnameL2,
        drawArea: data,
        publlicFileId: drawFileId + ''
      }
      this.$emit('ok', { building, position, submitNow: true })
      this.lineDraw.show = false
    }
  }
}
</script>
<style lang="scss" scoped>
.building-list {
  .title {
    color: #333;
    font-weight: bold;
    margin: 10px 0;
  }
  .list {
    display: flex;
    flex-wrap: wrap;
  }
  .item {
    width: 70px;
    font-size: 12px;
    text-align: center;
    margin: 5px;
    padding: 10px;
    box-sizing: content-box;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    &:hover,
    &.active {
      background-color: #e0eefd;
    }
  }
  .icon {
    font-size: 50px;
    background-color: #e0eefd;
    border-radius: 6px;
    padding: 10px;
    margin-bottom: 5px;
  }
}
</style>
